﻿using MaterialManagement.API.Application.Command.MesWorkOrder;
using MaterialManagement.Domain.MesWorkOrder;
using MaterialManagement.ErrorCode;
using MaterialManagement.Infrastructure.Implement;
using MediatR;

namespace MaterialManagement.API.Application.Handler.MesWorkOrder
{
    public class DeleteBOMHandle : IRequestHandler<DeleteBOMCommand, APIResult<int>>
    {
        private readonly DatabaseContext database;

        public DeleteBOMHandle(DatabaseContext database)
        {
            this.database = database;
        }
        public Task<APIResult<int>> Handle(DeleteBOMCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            var res = database.SqlSugar.Queryable<BOMInformationModel>().Where(x=>x.BOMCode == request.BOMCode).First();
            if (res == null)
            {
                result.Message = "找不到此BOM";
                result.Code = APIEnum.Fail;
                return Task.FromResult(result);
            }
            res.IsDel = true;
            int r = database.SqlSugar.Updateable(res).ExecuteCommand();
            if (r > 0)
            {
                result.Message = "删除成功";
                result.Code = APIEnum.Ok;
                result.Data = r;
                BOMLogsModel model = new BOMLogsModel()
                {
                    Message = "删除成功",
                    Operator = "李四",
                    OperationTime = DateTime.Now,
                };
                database.SqlSugar.Insertable(model).ExecuteCommand();
            }
            else
            {
                result.Message = "删除失败";
                result.Code = APIEnum.Fail;
                result.Data = r;
            }
            return Task.FromResult(result);
        }
    }
}
